#include "NextTurn.hh"
#include "Done.hh"
#include "StateChanged.hh"
#include "XmlServerThread.hh"
#include "../Exception.hh"

using namespace Network;
using namespace World;

spNextTurn NextTurn::construct(QDomElement const& message) {
    DONTCARE(message);
    return spNextTurn(new NextTurn());
}

NextTurn::NextTurn() {}

void NextTurn::process_on_server(XmlServerThread& thread) {
    if (thread.get_state() != GAME)
        throw NonFatalProtocolError("game.next_turn unexpected");

    thread.set_state(WAITING);
    spPlayer player = thread.get_player();
    spGalaxy galaxy = player->get_galaxy();
    bool nextTurn = galaxy->inc_next_turn_ctr();
    Done const done(true, "game.next_turn ok");
    done.send_to(*thread.get_socket());

    if (nextTurn) {
        // TODO megváltozott játék állapot elküldése
        PlayerMapByUser players = galaxy->get_players();
        StateChanged stateChanged(*galaxy);

        for (
          PlayerMapByUser::iterator p = players.begin();
          p != players.end();
          ++p
        ) {
            pXmlServerThread sthread = XmlServerThread::select(p.value());

            if (sthread) {
                sthread->set_state(GAME);
                stateChanged.send_to(*sthread->get_socket());
            }
        }
    }
}

QDomDocument NextTurn::to_xml() const {
    QDomDocument doc;
    QDomElement game = doc.createElement("game");
    QDomElement nextTurn = doc.createElement("next_turn");
    doc.appendChild(game);
    game.appendChild(nextTurn);
    return doc;
}
